package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Objects;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 新增入住申请
     *
     * @param dto 入住申请参数
     */
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.校验老人是否已入住 判断身份证号是否存在于已经启用的老人的表中
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 1); //在已启用的老人里查询 不为空就证明已入住，抛异常告诉前端 否则就接下来操作
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("该老人已入住");
        }


        //2.更新床位状态为已入住  dto.入住配置表里的床位Id
        // 拿到bed 对象
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3,新增或修改老人信息   参数：老人表+冗余字段 床位编号 床位Id
        Elder elder1 = updateOrAddElder(dto.getCheckInElderDto(), bed);
        //4.新增签约  参数：老人对象 dto
        insertContract(elder1, dto);
        //5.新增入住信息 参数 老人对象 dto
        CheckIn checkIn = insertCheckIn(elder1, dto);
        //6.新增入住配置  参数：入住配置表
        insertCheckInConfig(checkIn, dto.getCheckInConfigDto());


    }

    /**
     * 新增入住配置
     *
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);

    }

    /**
     * 新增入住信息
     *
     * @param elder1
     * @param dto
     */
    private CheckIn insertCheckIn(Elder elder1, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder1.getName());
        checkIn.setElderId(elder1.getId());
        checkIn.setIdCardNo(elder1.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder1.getBedNumber());
        checkIn.setStatus(0);


        //7.保存老人家属信息
        // 老人家属信息只用于数据展示, 转换为JSON字符串, 并存入CheckIn表的remark字段中.
        // 对象转JSON
        String jsonString = JSON.toJSONString(dto.getElderFamilyDtoList());
        checkIn.setRemark(jsonString);
        // JSON转对象
        List<ElderFamilyDto> elderFamilyDtos = JSON.parseArray(jsonString, ElderFamilyDto.class);
        System.out.println(elderFamilyDtos);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增或修改老人信息
     *
     * @param checkInElderDto
     * @param bed
     */
    private Elder updateOrAddElder(CheckInElderDto checkInElderDto, Bed bed) {
        //把参数传给 Elder对象
        // Elder 里面有床位编号 床位Id
        //checkInElderDto 里面没有
        Elder e = new Elder();
        BeanUtils.copyProperties(checkInElderDto, e);
        e.setBedId(bed.getId());
        e.setBedNumber(bed.getBedNumber());
        e.setStatus(1);
        //检查禁用状态下是否存在该老人 没有就新增 有就修改
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 0);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(elder)) {
            //新增
            //elderMapper.insertElder(e); 这是mybatis的 不用
            elderMapper.insert(e);
        } else {
            // 非空，修改
            e.setId(elder.getId()); //?
            elderMapper.updateById(e);
        }
        return e;

    }

    private void insertContract(Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        //从入住配置中获取开启和结束时间
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setEndDate(endDate);
        //判断合同状态
        if (startDate.isBefore(LocalDateTime.now())) {
            contract.setStatus(1);
        } else {
            contract.setStatus(0);
        }
        //保存合同
        contractMapper.insert(contract);
    }

    /**
     * 获取入住详情
     *
     * @param id
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public CheckInDetailVo getdetail(Long id) {
        //获取入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);

        //获取老人信息

        //创建CheckInDetailVo 对象
        CheckInDetailVo vo = new CheckInDetailVo();

        CheckInElderVo elderVo = new CheckInElderVo();
        //注意不能用 CheckInElderVo checkInElderVo = vo.getCheckInElderVo(); 这是null
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());

        //这里是因为前端显示的前几个老人，没有入住详情，所以这里要判断 我们自己手动加的会有入住详情
        if (elder != null) {
            BeanUtils.copyProperties(elder, elderVo); //source, target
            int age = IDCardUtils.getAgeFromIDCard(elder.getIdCardNo());
            elderVo.setAge(age);
            //封装进CheckInDetailVo
            vo.setCheckInElderVo(elderVo);
        }

        //获取合同信息
        Contract contract = contractMapper.selectContractByElderId(elder.getId());
        //封装进vo
        vo.setContract(contract);

        //获取入住配置
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckIn(checkIn.getId());
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        vo.setCheckInConfigVo(checkInConfigVo);

        //获取老人家属信息
        String elderFamilyJson = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilys = JSON.parseArray(elderFamilyJson, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilys);

        //返回CheckInDetailVo
        return vo;
    }
}
